package com.das.mechanic_base.widget;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.das.mechanic_base.R;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.alone.SpeechBean;
import com.das.mechanic_base.bean.main.CarBodyTextBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.X3StringUtils;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.umeng.analytics.MobclickAgent;

import java.util.List;
public class X3BottomHomeCarOwnerTextDialog extends X3BaseBottomSheetDialog implements View.OnClickListener,TextWatcher {

    private TextView tv_affirm;
    private TextView tv_cancel;
    private TextView tv_clear;
    private TextView tv_num;
    private EditText et_input;
    private TextView tv_title;
    private TextView tv_sound;
    private LinearLayout ll_start;
    private X3AloneSoundView as_view;
    private TextView tv_end;
    private long receiveId;
    private SpeechRecognizer mIat;
    private InputMethodManager imm;

    public X3BottomHomeCarOwnerTextDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        tv_clear = getView(R.id.tv_clear);
        tv_cancel = getView(R.id.tv_cancel);
        tv_affirm = getView(R.id.tv_affirm);
        tv_num = getView(R.id.tv_num);
        et_input = getView(R.id.et_input);
        tv_title = getView(R.id.tv_title);
        tv_sound = getView(R.id.tv_sound);
        ll_start = getView(R.id.ll_start);
        as_view = getView(R.id.as_view);
        tv_end = getView(R.id.tv_end);

        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

        et_input.addTextChangedListener(this);
        et_input.setOnClickListener(this);
        tv_end.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        tv_clear.setOnClickListener(this);
        tv_affirm.setOnClickListener(this);
        tv_sound.setOnClickListener(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_home_car_bottom_owner_text_dialog;
    }

    public void setContentText(String content) {
        if (X3StringUtils.isEmpty(content)) {
            return;
        }
        et_input.setText(content);
        et_input.setSelection(content.length());
    }

    @Override
    public void show() {
        super.show();
        tv_clear.performClick();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_affirm) {/**
         * 确定车主备注内容
         */
            dismiss();
            CarBodyTextBean bodyTextBean = new CarBodyTextBean();
            bodyTextBean.remark = et_input.getText().toString();
            NetWorkHttp.getApi().saveOrUpdateRemark(receiveId, bodyTextBean)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(((X3IBaseView) mContext).bindToLife())
                    .subscribe(new HttpCallBack<Object>() {
                        @Override
                        protected void onDone(Object o) {
                            if (iOnRefresh != null) {
                                iOnRefresh.iOnRefreshData();
                            }
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });
        } else if (id == R.id.tv_clear) {/**
         * 清空车主内容
         */
            et_input.setText("");
        } else if (id == R.id.tv_end || id == R.id.et_input) {// 停止语音识别
            isShowSound(false);
            if (mIat != null) {
                mIat.stopListening();
                mIat = null;
            }
        } else if (id == R.id.tv_cancel) {
            dismiss();
        } else if (id == R.id.tv_sound) {// 开启语音识别
            XXPermissions.with((Activity) mContext)
                    .permission(Permission.RECORD_AUDIO)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            if (all) {
                                startSoundEdit();
                            } else {
                                XXPermissions.startPermissionActivity(mContext, permissions);
                            }
                        }

                        @Override
                        public void onDenied(List<String> permissions, boolean never) {
                            XXPermissions.startPermissionActivity(mContext, permissions);
                        }
                    });
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String content = editable.toString();

        tv_clear.setVisibility(X3StringUtils.isEmpty(content) ? View.GONE : View.VISIBLE);
        if (X3StringUtils.isEmpty(content)) {
            tv_num.setText("0/1000");
        }else {
            tv_num.setText(content.length() + "/1000");
        }
    }

    public void showReceiveBaseId(long receiveId,String title) {
        this.receiveId = receiveId;
    }

    X3BottomHomeTyreDialog.IOnRefresh iOnRefresh;

    public void setiOnRefresh(X3BottomHomeTyreDialog.IOnRefresh iOnRefresh) {
        this.iOnRefresh = iOnRefresh;
    }

    /**
     * 刷新数据
     */
    public interface IOnRefresh {
        void iOnRefreshData();
    }

    private Handler mHandler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            et_input.setFocusable(true);
            et_input.setFocusableInTouchMode(true);
            et_input.requestFocus();
        }
    };

    /**
     * true ? 相当于点击了语音输入 显示语音输入的相关布局 ： 显示创建任务的布局
     *
     * @param showSound
     */
    private void isShowSound(boolean showSound) {

        ll_start.setVisibility(showSound ? View.VISIBLE : View.GONE);
        tv_sound.setVisibility(showSound ? View.GONE : View.VISIBLE);
        if (showSound) {
            as_view.startAnim();
            imm.hideSoftInputFromWindow(et_input.getWindowToken(), 0);

        } else {
            as_view.stopAnim();
            et_input.requestFocus();
            imm.showSoftInput(et_input, 0);
        }
    }

    /**
     * 语音听写
     */
    private void startSoundEdit() {
        mIat = SpeechRecognizer.createRecognizer(mContext, i -> Log.e("SSSS", "初始化：" + i));

        //设置语法ID和 SUBJECT 为空，以免因之前有语法调用而设置了此参数；或直接清空所有参数，具体可参考 DEMO 的示例。
        mIat.setParameter(SpeechConstant.CLOUD_GRAMMAR, null);
        mIat.setParameter(SpeechConstant.SUBJECT, null);
        //设置返回结果格式，目前支持json,xml以及plain 三种格式，其中plain为纯听写文本内容
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        //此处engineType为“cloud”
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, "cloud");
        //设置语音输入语言，zh_cn为简体中文
        if (LanguageUtiles.isZhRCN()) {
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        }else {
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        }
        //设置结果返回语言
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
        //取值范围{1000～10000}
        mIat.setParameter(SpeechConstant.VAD_BOS, "10000");
        //设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
        //自动停止录音，范围{0~10000}
        mIat.setParameter(SpeechConstant.VAD_EOS, "10000");
        //设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");

        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

        //开始识别，并设置监听器
        mIat.startListening(new RecognizerListener() {
            @Override
            public void onVolumeChanged(int i, byte[] bytes) {

            }

            @Override
            public void onBeginOfSpeech() {
                isShowSound(true);
            }

            @Override
            public void onEndOfSpeech() {
                isShowSound(false);
            }

            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                if (X3BottomHomeCarOwnerTextDialog.this == null) {
                    return;
                }
                if (!X3BottomHomeCarOwnerTextDialog.this.isShowing()) {
                    return;
                }
                SpeechBean speechBean = new Gson().fromJson(recognizerResult.getResultString(), SpeechBean.class);
                List<SpeechBean.WsBean> ws = speechBean.getWs();
                String strContent = "";
                for (SpeechBean.WsBean wsBean : ws) {
                    strContent = strContent + wsBean.getCw().get(0).getW();
                }
                String content = et_input.getText().toString() + strContent;
                et_input.setText(content);
                if (!X3StringUtils.isEmpty(content)) {
                    if (content.length() < 1000) {
                        et_input.setSelection(content.length());
                    }
                }

            }

            @Override
            public void onError(SpeechError speechError) {

            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {

            }
        });
    }

    @Override
    public void dismiss() {
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
        }
        if (mIat != null) {
            isShowSound(false);
            mIat.stopListening();
        }
        super.dismiss();
    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("初检信息输入车主备注弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("初检信息输入车主备注弹窗");
    }
}
